﻿using FluentNHibernate.Cfg;
using FluentNHibernate.Cfg.Db;
using NHibernate;
using NHibernate.Tool.hbm2ddl;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;
using System.Text;
using System.Threading.Tasks;

namespace YYSite.Common.NHibernate
{
    public interface INHFluentConfiguration
    {
        ISessionFactory GetSessionFactory();
    }


    public class NHFluentConfiguration : INHFluentConfiguration
    {
        private FluentConfiguration Configuration;
        private ISessionFactory SessionFactory;

        public NHFluentConfiguration(IPersistenceConfigurer persistenceConfigurer, params Assembly[] assemblies)
        {
            this.Configuration = Fluently.Configure()
                .Database(persistenceConfigurer)
            .Mappings(m =>
            {
                foreach (var assembly in assemblies)
                {
                    m.FluentMappings.AddFromAssembly(assembly);
                }
            })
            .ExposeConfiguration(cfg => new SchemaUpdate(cfg)
                        .Execute(false,true));
            this.SessionFactory= this.Configuration.BuildSessionFactory();
        }

        public ISessionFactory GetSessionFactory()
        {
            return this.SessionFactory;
        }
    }

}
